package com.thiruvathukal.examples.sax;

/*
 * XML code examples by George K. Thiruvathukal. Unless noted otherwise
 * this code is covered by GPLv2. We are still working on the licensing
 * text and will update all code and documentation shortly.
 */

import java.io.Reader;

import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

/**
 * This uses the an adapter to translate from sax events to
 * BetterXmlContentHandler events.
 * 
 * @see BetterXmlContentHandler
 * @see Sax2BetterXmlContentHandlerAdapter
 */
public class XmlParser {
	private XMLReader xmlReader;
	private ContentHandler handler;

	/**
	 * Create a new xml parser.
	 * 
	 * @throws BetterXmlException
	 */
	public XmlParser() {
		try {
			xmlReader = XMLReaderFactory.createXMLReader();
			xmlReader
					.setFeature("http://xml.org/sax/features/namespaces", true);
			xmlReader.setFeature(
					"http://xml.org/sax/features/namespace-prefixes", true);
		} catch (SAXException e) {
			throw new RuntimeException(e);
		}
	}

	public void parse(Reader reader) {
		handler = new TraceHandler();
		xmlReader.setContentHandler(handler);

		try {
			// xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler",
			// handler);
			xmlReader.parse(new InputSource(reader));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
